C++ program...overshoots? [migrated]

Posted by Zdrok on Programmers See other posts from Programmers or by Zdrok
Published on 2011-12-01T02:39:22Z Indexed on 2011/12/01 10:22 UTC
Read the original article Hit count: 239

Filed under:
|

I'm decent at C++, but I may have missed some nuance that applies here. Or maybe I completely missed a giant concept, I have no idea. My program was instantly crashing ("blah.exe is not responding") about 1/5 times it was run (other times it ran completely fine) and I tracked the problem down to a constructor for a world class that was called once in the beginning of the main function. Here is the code (in the constructor) that causes the problem:

int ii;
for(ii=0;ii<=255;ii++)
{
    cout<<"ent "<<ii<<endl;
    entity_list[ii]=NULL;
}
for(ii=0;ii<=255;ii++)
{
    cout<<"sec "<<ii<<endl;
    sector_list[ii]=NULL;
}
entity_list[0] = new Entity(0,0);
entity_list[0]->_world = this;

Specifically the second for loop. The cout references are new for the sake of telling where it is having trouble. It would print the entire "ent 1" to "ent 255" and then "sec 1" to "sec 255" and then crash right after, as if it was going for a 257th run through of the second for loop. I set the second for loop to go until "ii<=254" which stopped all crashes. Does C++ code tend to "overshoot" for loops or something? What is causing it to crash at this specific loop seemingly at random?

By the way, entity_list and sector_list point to classes called Entity and Sector, respectively, but they are not constructing anything so I didn't think it would be relevant. I also have a forward declaration for the Entity class in a header for this, but since none were being constructed I didn't think it was relevant either.

EDIT: It was due to the new Entity line, I assumed wrongly that the fact that altering the for statement to 254 fixed the crashes meant that it had to be there. I still don't understand why the for loop is related, though.

© Programmers or respective owner

Related posts about c++

Related posts about debugging